package com.gxh.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.gxh.context.BaseContext;
import com.gxh.dto.PageQueryDTO;
import com.gxh.dto.UserHistoryDTO;
import com.gxh.dto.UserHistoryPageQueryDTO;
import com.gxh.entity.UserHistory;
import com.gxh.mapper.MachineMapper;
import com.gxh.mapper.UserHistoryMapper;
import com.gxh.result.PageResult;
import com.gxh.service.UserHistoryService;
import com.gxh.vo.MachineItemVO;
import com.gxh.vo.UserHistoryVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class UserHistoryServiceImpl implements UserHistoryService {

    @Autowired
    private UserHistoryMapper userHistoryMapper;
    @Autowired
    private MachineMapper machineMapper;

    /**
     * 添加用户历史记录
     * @param userHistoryDTO
     */
    public void add(UserHistoryDTO userHistoryDTO) {
        Long userId = BaseContext.getCurrentId();
        Long machineId = userHistoryDTO.getMachineId();
        //判断是否存在记录
        QueryWrapper<UserHistory> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("machine_id", machineId);
        UserHistory userHistory = userHistoryMapper.selectOne(queryWrapper);
        if (userHistory!= null) {
            userHistory.setCreateTime(LocalDateTime.now());
            userHistoryMapper.updateById(userHistory);
        }
        else {
            UserHistory history = UserHistory.builder()
                    .userId(userId)
                    .machineId(machineId)
                    .createTime(LocalDateTime.now())
                    .build();
            userHistoryMapper.insert(history);
        }
    }

    @Override
    public PageResult userPage(PageQueryDTO pageQueryDTO) {
        Long userId = BaseContext.getCurrentId();
        PageHelper.startPage(pageQueryDTO.getPage(), pageQueryDTO.getPageSize());
        //获取用户历史记录合表查询
        Page<MachineItemVO> page = userHistoryMapper.pageQueryWithMachine(userId);
        Long total = page.getTotal();
        List<MachineItemVO> records = page.getResult();
        return new PageResult(total, records);
    }

    @Override
    public PageResult pageQuery(UserHistoryPageQueryDTO userHistoryPageQueryDTO) {
        PageHelper.startPage(userHistoryPageQueryDTO.getPage(), userHistoryPageQueryDTO.getPageSize());
        Page<UserHistoryVO> page = userHistoryMapper.pageQuery(userHistoryPageQueryDTO);
        Long total = page.getTotal();
        List<UserHistoryVO> records = page.getResult();
        return new PageResult(total, records);
    }
}
